﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Library;
using DataConnector;
using LabManager.UserControls.Tabs.Templates;
using Equin.ApplicationFramework;
using System.Data.Entity;
using Microsoft.VisualBasic;

namespace LabManager.UserControls.Tabs.Masterdata
{
    public partial class TabUser : TabTemplate
    {
        private SimpleAES simpleAes = new SimpleAES();
        private BindingSource bindingSource = new BindingSource();
        private BindingListView<V_UserList> bindingList;
        private int selectedID = -1;

        public TabUser()
        {
            InitializeComponent();
        }

        public override void Load()
        {
            SetTexts();
            LoadDepartments();
            LoadUserGroups();
            LoadUserList();
        }

        #region Helper

        private void LoadUserList()
        {
            // Get new Entities from View
            DataConnectorLayer.Instance.R_V_UserList = new Repository<V_UserList, DbContext>(new DbContext(Helper.ENTITY_NAME));
            bindingList = new BindingListView<V_UserList>(DataConnectorLayer.Instance.R_V_UserList.FindAll(x => x.UserID > 0).ToList<V_UserList>());
            bindingSource.DataSource = bindingList;
            dgMain.DataSource = bindingSource;
            bnNavi.BindingSource = bindingSource;
            
            if (dgMain.Rows.Count > 0)
            {
                selectedID = (int)dgMain.Rows[0].Cells[0].Value;
            }

            dgMain_SelectionChanged(null, null);
        }

        private void LoadDepartments()
        {
            var departments = new BindingListView<Department>(DataConnectorLayer.Instance.R_Department.FindAll(x => x.DepartmentID > 0).ToList<Department>());

            cbDepartment.DataSource = departments;
            cbDepartment.ValueMember = "DepartmentID";
            cbDepartment.DisplayMember = "DepartmentName";
        }

        private void LoadUserGroups()
        {
            var userGroups = new BindingListView<UserGroup>(DataConnectorLayer.Instance.R_UserGroup.FindAll(x => x.UserGroupID > 0).ToList<UserGroup>());

            cbGroup.DataSource = userGroups;
            cbGroup.ValueMember = "UserGroupID";
            cbGroup.DisplayMember = "UserGroupName";
        }

        private void SetTexts()
        {
            //TODO 
        }

        #endregion

        #region Events

        private void btNew_Click(object sender, EventArgs e)
        {
            string input = Interaction.InputBox("Please enter a loginname for your new user", "New user", "");

            if (!string.IsNullOrWhiteSpace(input))
            {
                if (DataConnectorLayer.Instance.R_User.FindOne(x => x.Login == input) != null)
                {
                    MessageBox.Show(string.Format("User '{0}' already exists", input), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    var departmentID = DataConnectorLayer.Instance.R_Department.FindOne().DepartmentID;
                    var userGroupID = DataConnectorLayer.Instance.R_UserGroup.FindOne().UserGroupID;

                    var item = new User() { Login = input, FirstName = Helper.EMPTY_STRING, LastName = Helper.EMPTY_STRING, Password = Helper.STANDARD_PW, DepartmentID = departmentID, UserGroupID = userGroupID, MailAddress = Helper.EMPTY_STRING, Active = false, };
                    DataConnectorLayer.Instance.R_User.Create(item);
                    DataConnectorLayer.Instance.R_User.SaveChanges();

                    LoadUserList();
                }
            }
        }

        private void dgMain_SelectionChanged(object sender, EventArgs e)
        {
            if (dgMain.SelectedRows.Count > 0)
            {
                var selectedRow = dgMain.SelectedRows[0];

                selectedID = (int)selectedRow.Cells[0].Value;
                tbLogin.Text = selectedRow.Cells[1].Value.ToString();
                tbPassword.Text = simpleAes.DecryptString(selectedRow.Cells[8].Value.ToString());
                tbFirstname.Text = selectedRow.Cells[2].Value.ToString();
                tbLastname.Text = selectedRow.Cells[3].Value.ToString();
                cbActive.Checked = selectedRow.Cells[6].Value != null;
                cbDepartment.Text = selectedRow.Cells[4].Value.ToString();
                cbGroup.Text = selectedRow.Cells[5].Value.ToString();
                tbEmail.Text = selectedRow.Cells[7].Value.ToString();

                // Delete button
                var hasProductStateTrail = DataConnectorLayer.Instance.R_ProductStateTrail.FindOne(product => product.User.UserID == selectedID) != null;
                var hasLoginTrail = DataConnectorLayer.Instance.R_LoginTrail.FindOne(trail => trail.User.UserID == selectedID) != null;
                btDelete.Enabled = !hasProductStateTrail && !hasLoginTrail;
                btUpdate.Enabled = true;
            }
            else
            {
                tbLogin.Text = string.Empty;
                tbPassword.Text = string.Empty;
                tbFirstname.Text = string.Empty;
                tbLastname.Text = string.Empty;
                cbActive.Checked = false;
                cbDepartment.Text = string.Empty;
                cbGroup.Text = string.Empty;
                tbEmail.Text = string.Empty;

                btUpdate.Enabled = false;
                btDelete.Enabled = false;
            }

            // New button
            var canCreateDepartment = DataConnectorLayer.Instance.R_Department.Set<Department>().Count() > 0;
            var canCreateUserGroup = DataConnectorLayer.Instance.R_Department.Set<UserGroup>().Count() > 0;
            btNew.Enabled = canCreateDepartment && canCreateUserGroup;
        }

        private void btUpdate_Click(object sender, EventArgs e)
        {
            var item = DataConnectorLayer.Instance.R_User.FindById(selectedID);

            item.FirstName = tbFirstname.Text != "" ? tbFirstname.Text : Helper.EMPTY_STRING;
            item.LastName = tbLastname.Text != "" ? tbLastname.Text : Helper.EMPTY_STRING;
            item.Active = cbActive.Checked;
            item.DepartmentID = (int)cbDepartment.SelectedValue;
            item.UserGroupID = (int)cbGroup.SelectedValue;
            item.MailAddress = tbEmail.Text != "" ? tbEmail.Text : Helper.EMPTY_STRING;
            item.Password = tbPassword.Text != "" ? simpleAes.EncryptToString(tbPassword.Text) : Helper.STANDARD_PW;

            DataConnectorLayer.Instance.R_User.Update(item);
            DataConnectorLayer.Instance.R_User.SaveChanges();

            LoadUserList();
        }

        private void btDelete_Click(object sender, EventArgs e)
        {
            var item = DataConnectorLayer.Instance.R_User.FindById(selectedID);
            DataConnectorLayer.Instance.R_User.Delete(item);
            DataConnectorLayer.Instance.R_User.SaveChanges();

            LoadUserList();
        }

        private void tbFilter_TextChanged(object sender, EventArgs e)
        {
            var search = tbFilter.Text.ToLower();

            bindingList.ApplyFilter(delegate(V_UserList user)
            {
                return  user.Login.ToLower().Contains(search) ||
                        user.Firstname.ToLower().Contains(search) ||
                        user.Lastname.ToLower().Contains(search) ||
                        user.DepartmentName.ToLower().Contains(search) ||
                        user.UserGroupName.ToLower().Contains(search);
            });
        }

        #endregion

    }
}